package com.example.demo.controller;

import com.example.demo.dto.SubmitAnswerRequest;
import com.example.demo.dto.UserStatsResponse;
import com.example.demo.entity.Exercise;
import com.example.demo.entity.Question;
import com.example.demo.entity.UserAnswer;
import com.example.demo.service.ExerciseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
public class ExerciseController {
    @Autowired
    private ExerciseService exerciseService;
    @Autowired
    private ExerciseService questionService;
    @Autowired
    private ExerciseService userAnswerService;
    @Autowired
    private ExerciseService userStatsService;

    @GetMapping("/exercises")
    public List<Exercise> getExercises() {
        return exerciseService.list();
    }

    @GetMapping("/exercises/{subject}")
    public List<Exercise> getExercisesBySubject(@PathVariable String subject) {
        return exerciseService.getExercisesBySubject(subject);
    }

    @GetMapping("/questions/{subject}")
    public List<Question> getQuestionsByExerciseId(@PathVariable int exerciseId) {
        return questionService.getQuestionsByExerciseId(exerciseId);
    }
    // 新增的根据 subject 获取问题列表的方法
    @GetMapping("/questions/subject/{subject}")
    public List<Question> getQuestionsBySubject(@PathVariable String subject) {
        return questionService.getQuestionsBySubject(subject);
    }

    @PostMapping("/user-answers")
    public void submitAnswers(@RequestBody SubmitAnswerRequest request) {
        List<UserAnswer> userAnswers = request.getUserAnswers();
        userAnswers.forEach(answer -> {
            answer.setUserId(request.getUserId());
            answer.setExerciseId(request.getExerciseId());
        });
        userAnswerService.submitAnswers(userAnswers);
    }

    @GetMapping("/user-stats/{userId}")
    public UserStatsResponse getUserStats(@PathVariable int userId) {
        return userStatsService.getUserStats(userId);
    }
}
